package net.csdn.business.common.utils;

import cn.hutool.http.HtmlUtil;
import net.csdn.business.common.constant.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author likun
 * @date 2022/5/9 14:40
 */
public class HtmlParserTextUtil {
    private static final Pattern EMPTY_PATTERN = Pattern.compile("\\s{2,}|\\t|\\r|\\n|\\r\\n");
    private static final String BLANK_MATCH_RULE = "\\s{2,}|\\n|↵|\\r|\\r\\n";
    private static final String SPACE_STR = "\\u00A0+";

    /**
     * 富文本提取文件简介
     *
     * @param htmlText   内容
     * @param maxSubSize 字数
     * @return String
     */
    public static String htmlParserText(String htmlText, int maxSubSize) {
        String imgReplaceText = StringUtils.EMPTY;

        String text = htmlTextSummary(htmlText);
        if (StringUtils.isNotBlank(text)) {
            text = replaceSpecialStr(text);
        }
        // 处理不间断空格nbsp,利用不间断空格的Unicode编码来移除它
        text = text.replaceAll(SPACE_STR, StringUtils.EMPTY);

        if (StringUtils.isBlank(text)) {
            if (StringUtils.isNotBlank(imgReplaceText)) {
                text += imgReplaceText;
            }
            return text;
        }

        if (NumberUtils.compare(text.length(), maxSubSize) >= CommonConstants.INT_ZERO) {
            return StringUtils.substring(text, CommonConstants.INT_ZERO, maxSubSize);
        }

        return text;
    }

    public static String htmlTextSummary(String htmlText) {
        if (StringUtils.isBlank(htmlText)) {
            return StringUtils.EMPTY;
        }
        return HtmlUtil.unescape(HtmlUtil.cleanHtmlTag(htmlText)).replaceAll(BLANK_MATCH_RULE, " ");
    }

    public static String contentSub(String text, int maxSubSize) {
        if (StringUtils.isBlank(text)) {
            return "";
        }

        text = StringUtils.trim(replaceSpecialStr(text));

        if (NumberUtils.compare(text.length(), maxSubSize) >= CommonConstants.INT_ZERO) {
            return StringUtils.substring(text, CommonConstants.INT_ZERO, maxSubSize);
        }
        return text;
    }

    public static String replaceSpecialStr(String str) {
        String repl = StringUtils.EMPTY;
        if (str != null) {
            Matcher m = EMPTY_PATTERN.matcher(str);
            repl = m.replaceAll(StringUtils.EMPTY);
        }
        return repl;
    }

    public static String htmlTextSummaryV2(String htmlText) {
        if (StringUtils.isBlank(htmlText)) {
            return StringUtils.EMPTY;
        }
        return HtmlUtil.escape(htmlText).replaceAll(BLANK_MATCH_RULE, " ");
    }

    public static String clearHtml(String content) {
        if (StringUtils.isBlank(content)) {
            return content;
        }
        return HtmlUtil.cleanHtmlTag(content);
    }
}
